package com.neuedu.web.servlet;

import com.neuedu.web.dao.UserDao;
import com.neuedu.web.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @auth 金山老师
 * title:   书籍代码
 * creatime: 2022-10-19 11:31
 * 描述 :
 */
@WebServlet(value = "/user")
public class UserServlet  extends HttpServlet {
    UserDao userDao = new UserDao();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    /**
     *   列表： http://localhost:8080/web/user
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String type = request.getParameter("_type");
        if(type == null || "list".equals(type)){
            this.list(request,response);
        }else if("toAdd".equals(type)){
            this.toAdd(request,response);
        }else if("save".equals(type)){
            this.save(request,response);
        }else if("delete".equals(type)){
            this.deleteById(request,response);
        }else if("toEdit".equals(type)){
            this.toEdit(request,response);
        }else if("update".equals(type)){
            this.update(request,response);
        }


    }

    private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //使用requests接受参数

        //getParameter 返回字符串形式的参数

        String id = request.getParameter("id");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String displayname = request.getParameter("displayname");
        String birthday = request.getParameter("birthday");
        String gender = request.getParameter("gender");
        String email = request.getParameter("email");
        String telephone = request.getParameter("telephone");
        String lastLogintime = request.getParameter("lastLogintime");

        //接收到的参数在控制台中输出
        System.out.println("username = " + username);
        System.out.println("password = " + password);
        System.out.println("displayname = " + displayname);
        System.out.println("birthday = " + birthday); //yyyy-MM-dd
        System.out.println("gender = " + gender);
        System.out.println("email = " + email);
        System.out.println("telephone = " + telephone);
        System.out.println("lastLogintime = " + lastLogintime);

        //保存到数据库中
        Date dataBirthDay = null;
        Date dataLastLogin = null;
        try {
            dataBirthDay = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        try {
            dataLastLogin = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(lastLogintime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String sql = "UPDATE  user SET `username` = ?, `displayname` = ?, " +
                "`password` = ?, `birthday` = ?, `gender` = ?,  `telephone` = ?,  `email` = ?, `last_logintime` = ? where id = ? ";
        try {
            int count = userDao.update(sql ,
                    username,
                    displayname,
                    password,
                    dataBirthDay,
                    gender,
                    telephone,
                    email,
                    dataLastLogin,
                    id
            );

            System.out.println("count = " + count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


        //告诉浏览器 重新请求一次 userlist

        // response.sendRedirect("http://www.baidu.com"); //相对路径
        // 获取上下文
        String contextPath  = request.getContextPath();//上下文
        response.sendRedirect(contextPath+"/user"); //相对路径

    }

    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws IOException {


        try {
            String id = request.getParameter("id");
            User user = userDao.selectOne(Integer.parseInt(id));

            //设置响应格式 为html
            response.setContentType("text/html;charset=utf8");
            // 设置响应编码
            response.setCharacterEncoding("utf-8");


            StringBuilder html = new StringBuilder();

            //action属性表示提交的路径
            html.append("  <h3>用户添加</h3>														");
            html.append("  	<form method='post' action='user'>                                          ");
            html.append("  	<input type='hidden' name='id' value='" + user.getId() + "' >	    ");
            html.append("  	<input type='hidden' name='_type' value='update' >	    ");
            html.append("  		<table width='500' border='1' cellpadding='0' cellspacing='0'>      ");

            html.append("  			<tr>                                                            ");
            html.append("  				<td>用户名</td>                                             ");
            html.append("  				<td><input type='text' name='username' value='" + user.getUsername() + "'></td>                ");
            html.append("  			</tr>                                                           ");
            html.append("  			<tr>                                                            ");
            html.append("  					<td>密码</td>                                           ");
            html.append("  				<td><input type='password' name='password' value='" + user.getPassword() + "' ></td>                ");
            html.append("  			</tr>                                                           ");
            html.append("  			<tr>                                                            ");
            html.append("  				<td>昵称</td>                                               ");
            html.append("  				<td><input type='text' name='displayname' value='" + user.getDisplayname() + "' ></td>             ");
            html.append("  			</tr>                                                           ");
            html.append("  			<tr>                                                            ");
            html.append("  					<td>birthday</td>                                       ");
            String strBirthday = "";
            if (user.getBirthday() != null) {
                strBirthday = new SimpleDateFormat("yyyy-MM-dd").format(user.getBirthday());
            }
            html.append("  				<td><input type='text' name='birthday' value='" + strBirthday + "' ></td>                ");
            html.append("  			</tr>                                                           ");
            html.append("  			<tr>                                                            ");
            html.append("  				<td>性别</td>                                               ");
            html.append("  				<td><input type='text' name='gender' value='" + user.getGender() + "' ></td>                  ");
            html.append("  			</tr>                                                           ");
            html.append("                                                                           ");
            html.append("  			<tr>                                                            ");
            html.append("  				<td>email</td>                                              ");
            html.append("  				<td><input type='text' name='email' value='" + user.getEmail() + "' ></td>                   ");
            html.append("  			</tr>                                                           ");
            html.append("  			<tr>                                                            ");
            html.append("  				<td>telephone</td>                                          ");
            html.append("  				<td><input type='text' name='telephone' value='" + user.getTelephone() + "' ></td>               ");
            html.append("  			</tr>                                                           ");
            html.append("  			<tr>                                                            ");
            html.append("  				<td>lastLogintime</td>                                      ");
            String strLastLogin = "";
            if (user.getLastLogintime() != null) {
                strLastLogin = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(user.getLastLogintime());
            }

            html.append("  				<td><input type='text' name='lastLogintime' value='" + strLastLogin + "' ></td>           ");
            html.append("  			</tr>                                                           ");
            html.append("  			<tr>                                                            ");
            html.append("  			<td colspan='2' align='center'>    <input type='submit' value='提交'>   <input type='reset'></td>                                    ");
            html.append("  			</tr>                                                           ");
            html.append("  		</table>                                                            ");
            html.append("                                                                           ");
            html.append("  	</form>                                                                ");

            PrintWriter out = response.getWriter();
            out.write(html.toString());
            out.flush();
            out.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }


    }

    private void deleteById(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //接收一个用户id
        String  id = request.getParameter("id");

        // 调用UserDao的删除
        int count = 0;
        try {
            count = userDao.deleteById(Integer.parseInt(id));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println("count = " + count);


        //重定向到UserList
        response.sendRedirect(request.getContextPath() +"/user");
    }

    private void save(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //使用requests接受参数

        //getParameter 返回字符串形式的参数

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String displayname = request.getParameter("displayname");
        String birthday = request.getParameter("birthday");
        String gender = request.getParameter("gender");
        String email = request.getParameter("email");
        String telephone = request.getParameter("telephone");
        String lastLogintime = request.getParameter("lastLogintime");

        //接收到的参数在控制台中输出
        System.out.println("username = " + username);
        System.out.println("password = " + password);
        System.out.println("displayname = " + displayname);
        System.out.println("birthday = " + birthday); //yyyy-MM-dd
        System.out.println("gender = " + gender);
        System.out.println("email = " + email);
        System.out.println("telephone = " + telephone);
        System.out.println("lastLogintime = " + lastLogintime);

        //保存到数据库中
        Date dataBirthDay = null;
        Date dataLastLogin = null;
        try {
            dataBirthDay = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        try {
            dataLastLogin = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(lastLogintime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String sql = "INSERT INTO `user` (  `username`, `displayname`, `password`, `birthday`, `gender`, `telephone`, `email`, `last_logintime`)  VALUES ( ?,?,?,?,?,?,?,?  )  ";
        try {
            int count = userDao.insert(sql ,
                    username,
                    displayname,
                    password,
                    dataBirthDay,
                    gender,
                    telephone,
                    email,
                    dataLastLogin
            );

            System.out.println("count = " + count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        // 获取上下文
        String contextPath  = request.getContextPath();//上下文
        // response.sendRedirect(contextPath+"/user?_type=list"); //相对路径
        response.sendRedirect(contextPath+"/user"); //相对路径

    }

    /**
     * 展示添加页面
     * @param request
     * @param response
     */
    private void toAdd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置响应格式 为html
        response.setContentType("text/html;charset=utf8");
        // 设置响应编码
        response.setCharacterEncoding("utf-8");


        StringBuilder html = new StringBuilder();

        //action属性表示提交的路径
        html.append("  <h3>用户添加</h3>														");
        html.append("  	<form method='post' action='user?_type=save'>                                          ");
        html.append("  		                                                                    ");
        html.append("  		<table width='500' border='1' cellpadding='0' cellspacing='0'>      ");
        html.append("  			<tr>                                                            ");
        html.append("  				<td>用户名</td>                                             ");
        html.append("  				<td><input type='text' name='username'></td>                ");
        html.append("  			</tr>                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  					<td>密码</td>                                           ");
        html.append("  				<td><input type='password' name='password'></td>                ");
        html.append("  			</tr>                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  				<td>昵称</td>                                               ");
        html.append("  				<td><input type='text' name='displayname'></td>             ");
        html.append("  			</tr>                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  					<td>birthday</td>                                       ");
        html.append("  				<td><input type='text' name='birthday'></td>                ");
        html.append("  			</tr>                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  				<td>性别</td>                                               ");
        html.append("  				<td><input type='text' name='gender'></td>                  ");
        html.append("  			</tr>                                                           ");
        html.append("                                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  				<td>email</td>                                              ");
        html.append("  				<td><input type='text' name='email'></td>                   ");
        html.append("  			</tr>                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  				<td>telephone</td>                                          ");
        html.append("  				<td><input type='text' name='telephone'></td>               ");
        html.append("  			</tr>                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  				<td>lastLogintime</td>                                      ");
        html.append("  				<td><input type='text' name='lastLogintime'></td>           ");
        html.append("  			</tr>                                                           ");
        html.append("  			<tr>                                                            ");
        html.append("  			<td colspan='2' align='center'>    <input type='submit' value='提交'>   <input type='reset'></td>                                    ");
        html.append("  			</tr>                                                           ");
        html.append("  		</table>                                                            ");
        html.append("                                                                           ");
        html.append("  	</form>                                                                ");

        PrintWriter out = response.getWriter();
        out.write(html.toString());
        out.flush();
        out.close();


    }


    //列表的方法
    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取响应对象 out
        //设置响应的类型
        // response.setContentType("text/plain"); //简单文本
        response.setContentType("text/html;charset=utf-8"); //文本---html


        //在响应内容之前，设置编码格式 contenttype
        response.setCharacterEncoding("utf-8");

        // response.getOutputStream()
        PrintWriter out = response.getWriter();



        try {
            UserDao userDao = new UserDao();
            String sql = " select * from user";
            Object[] params = {};
            List<User> users = userDao.selectList(sql, params);

            StringBuilder html = new StringBuilder();
            html.append( "  <a href='user?_type=toAdd'>添加</a> 							");
            html.append( "  <table width='100%' border='1' cellpadding='0' cellspacing='0' >							");
            html.append( "  	<tr>                      "  );
            html.append( "  		<td>序号</td>         "  );
            html.append( "  		<td>用户名</td>       "  );
            html.append( "  		<td>密码</td>         "  );
            html.append( "  		<td>昵称</td>         "  );
            html.append( "  		<td>出生日期</td>     "  );
            html.append( "  		<td>email</td>        "  );
            html.append( "  		<td>操作</td>        "  );
            html.append( "  	</tr>                     "  );
            for (int i = 0; i < users.size(); i++) {
                User user = users.get(i);
                html.append( "  	<tr>                      "  );
                html.append( "  		<td>"+i+"</td>            "  );
                html.append( "  		<td>"+user.getUsername()+"</td>        "  );
                html.append( "  		<td>"+user.getPassword()+"</td>        "  );
                html.append( "  		<td>"+user.getDisplayname()+"</td>        "  );
                html.append( "  		<td>"+user.getBirthday()+"</td>        "  );
                html.append( "  		<td>"+user.getEmail()+"</td>        "  );
                html.append( "  		<td><a href='user?_type=delete&id="+user.getId()+"' >删除</a> &nbsp;&nbsp; " +
                        " <a href='user?_type=toEdit&id="+user.getId()+"' >更新</a></td>        "  );

            }
            html.append( "                                "  );
            html.append( "  	</table>                  "  );

            // out.输出 html
            out.write(html.toString());

            out.flush();
            out.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


}
